/*
 * @Author: your name
 * @Date: 2021-08-05 11:14:37
 * @LastEditTime: 2021-08-06 16:43:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \总练习区\sorket\index.js
 */
const port = 3058
const express = require('express')
const app = express()


let server = app.listen(port)
let io = require('socket.io')().listen(server,{cors:true})


const socketList = {}
let socketLength = 0


io.on('connection',(socket)=>{
    socket.emit('getSocketId',socket.id)
    // 发送消息
    socket.on('send',(data)=>{
        socket.broadcast.emit('reception',data)
    })
    // 有人加入聊天
    socket.on('join',data=>{
        socketList[socket.id] = data.name
        socketLength++
        let joinData = {
            ...data,
            length:socketLength
        }
        socket.broadcast.emit('join',joinData)
        socket.emit('join',joinData)
    })
    // 有人离开聊天
    socket.on('disconnect',()=>{
        if(socketList.hasOwnProperty(socket.id)){
            let data = socketList[socket.id]
            delete socketList[socket.id]
            socketLength--
            socket.broadcast.emit('close',{
                name:data,
                id:socket.id,
                length:socketLength
            })
        }
        
    })
})
